<template>
  <div class="login">
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-2 col-md-offset-5 col-xs-6 col-xs-offset-3">
          <img src="../../assets/logo1.png" class="text-center" style="width: 50%;margin: 25% 25% 0 25%;">
          <h3 class="text-center" style="white-space: nowrap">黑侠的小圈子</h3>
        </div>
      </div>
      <div class="row">
        <div class="col-md-6 col-md-offset-3">
          <van-form @submit="onSubmit" >
            <van-field
                v-model="username"
                name="用户名"
                label="用户名"
                placeholder="用户名"
                :rules="[{pattern:userpattern,required: true, message: '请输入2-10位无特殊字符组成的用户名' }]"
            />
            <van-field
                v-model="password"
                type="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ pattern: passwordpattern,required: true, message: '请输入6-10位无符号组成的密码' }]"
            />
            <div style="margin: 16px;">
              <van-button :loading="logloading" loading-text="登录中..." block round size="large" type="info" native-type="submit">登录</van-button>
            </div>

            <div style="float: right;padding:0 20px;display: flex;justify-content: space-between;width: 100%">
              <router-link to="/register"><small>还没有账号？立即注册</small></router-link>
              <router-link to="/emailcode"><small>忘记密码</small></router-link>
            </div>

            <div class="wxlogin" @click="goWx">
              <div class="icon"></div>
              <div class="tip">微信快捷登录</div>
            </div>
          </van-form>
        </div>
      </div>
    </div>
    <transition name="popshow">
      <div class="wxpop" v-if="not_subscription">
        <div class="wxpop_main">
          <div class="wxpop_title">{{wxpopTip.t}}</div>
          <div class="wxpop_title">{{wxpopTip.c}}</div>
          <div class="wxpop_title">{{wxpopTip.b}}</div>
          <div class="wxpop_wxqr">
            <img src="../../assets/wxqr.jpg" width="auto" height="100%">
          </div>
          <div class="wxpop_close" @click="wxClose" :class="{an_wxpop_close:close}"></div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import qs from 'qs';
import {userLogin, wxLogin} from "../../utils/api";
import {sleep} from "../../utils/util";
export default {
  name: "Login",
  data(){
    return {
      username:'',
      password:'',
      userpattern:/^[(a-zA-Z0-9\u4e00-\u9fa5)]{2,10}$/,
      passwordpattern:/^[0-9a-zA-Z]{6,10}$/,
      beforfrom:'',
      logloading:false,
      not_subscription:false,
      wxpopTip:{
        t:'',
        c:'',
        b:''
      },
      close:false
    }
  },
  methods:{
    onSubmit(){
      this.logloading=true
      let href = localStorage.getItem('href')
      userLogin(qs.stringify({
        username:this.username,password:this.password
          })
      ).then(response=>{
        if(response.status===200){
          this.logloading=false
          this.$toast.success('登录成功');
          this.$store.commit('setUserName',response.username);
          this.$store.commit('setUserqx',response.q);
          this.$store.dispatch('createHeader');
          if(!response.email){
            this.$confirm('未绑定找回密码的邮箱', '提示', {
              distinguishCancelAndClose: true,
              confirmButtonText: '前去绑定',
              cancelButtonText: '暂不绑定'
            })
            .then(() => {
              //绑定
              this.$router.push('/bindemail')
            })
            .catch(action => {
              //不绑定
              if(href){
                localStorage.removeItem('href')
                location.href = href
                return
              }
              if(this.beforfrom!=="/register" && this.beforfrom!=="/login" && this.beforfrom!=="/emailcode" && this.beforfrom!=="/forget"){
                this.$router.go(-1); //返回上级路由
              }
              this.$router.replace("/") //如果没有返回，我们就指定跳转到首页
            });
          }else{
            if(href){
              localStorage.removeItem('href')
              location.href = href
              return
            }
            if(this.beforfrom!=="/register" && this.beforfrom!=="/login" && this.beforfrom!=="/emailcode" && this.beforfrom!=="/forget"){
              this.$router.go(-1); //返回上级路由
            }
            this.$router.replace("/") //如果没有返回，我们就指定跳转到首页
          }
        }else if(response.status===120){
          this.$toast.fail('用户名\n密码错误')
          this.logloading=false
          this.password="";
        }else if(response.status===999){
          this.$toast.fail('未知错误')
          this.logloading=false
          this.password="";
        }
      }).catch(error=>{
        console.log(error);
        this.logloading=false
      })
    },
    goWx(){
      window.location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx325d8a04a600270c&redirect_uri="+window.location.origin+'/login' +
          "&response_type=code&scope=snsapi_userinfo&state=cc#wechat_redirect")
    },
    wxClose(){
      this.close = true
      sleep(300).then(()=>{
        this.not_subscription = false
      })
    }
  },
  created() {
    //如果存在code 那么就发送给后端
    let ua = navigator.userAgent.toLowerCase();
    let isWeixin = ua.indexOf('micromessenger') != -1;
    let href = localStorage.getItem('href')
    // 如果不是微信浏览器就不管是否存在参数
    if(this.$route.query.code && !localStorage.getItem('userToken') && isWeixin){
      /*今天是否为今天第一次登录*/
      let day = 0
      let localStorageValue = localStorage.getItem('dailyWxLogin')
      if(!localStorageValue){
        day = 1
      }else{
        if(new Date().getDate()!=new Date(localStorageValue-0).getDate()){
          day = 1
        }else{
          /*同一天 进一步判断是否为当天*/
          let _time = new Date()
          if(!(localStorageValue-0>=new Date(_time.setDate(_time.getDate())).setHours(0,0,0,0) && localStorageValue-0<new Date(_time.setDate(_time.getDate()+1)).setHours(0,0,0,0))){
            day = 1
          }
        }
      }

      wxLogin({code:this.$route.query.code,day}).then(response=>{
        delete this.$route.query.code;
        //120 code无效
        //如果状态为158 那么需要保存openid 并且带到绑定页面或者注册页面
        //如果为200 那么找到用户
        if(response.status===200) {
          if(response.wxdaily){
            if(response.wxdaily!=0){
              this.$notify({
                title: '登录成功',
                message: `恭喜你获得${response.wxdaily}元余额`,
                type: 'success'
              });
            }
            localStorage.setItem('dailyWxLogin',new Date().getTime()+'')
          }else{
            this.$toast.success('登录成功');
          }
          setTimeout(()=>{
            this.$store.commit('setUserName', response.username);
            this.$store.commit('setUserqx', response.q);
            this.$store.dispatch('createHeader');
            if(href){
              localStorage.removeItem('href')
              location.href = href
              return
            }
            if (this.beforfrom !== "/register" && this.beforfrom !== "/login") {
              this.$router.go(-1); //返回上级路由
            }
            this.$router.replace("/") //如果没有返回，我们就指定跳转到首页
          },2000)
        }else if(response.status==158){
          //携带id去跳转到页面
          this.$confirm('首次微信登录，请先绑定或者注册账号', '确认信息', {
            distinguishCancelAndClose: true,
            confirmButtonText: '绑定账号',
            cancelButtonText: '注册账号'
          })
              .then(() => {
                //绑定
                this.$router.push({path:'/userbind',query:{id:response.openid}})
              })
              .catch(action => {
                //注册
                this.$router.push({path:'/register',query:{id:response.openid}})
              });
        }else if(response.status==120){
          //code无效
          this.$toast.fail(response.msg);
          //刷新页面 删除code
        }else if(response.status===160){
          this.not_subscription = true
          let t = '你怎么不关注公众号？'
          let c = '你怎么敢的？？？'
          let b = '速度给我关注上！！！'
          sleep(600).then(() => {
            let index = 0
            let time = null
            if(time==null){
              time = setInterval(()=>{
                index++
                this.wxpopTip.t = t.slice(0, index)
                if(index==10){
                  clearInterval(time)
                }
              },100)
            }
            return sleep(1100)
          }).then(()=>{
            let index = 0
            let time = null
            if(time==null){
              time = setInterval(()=>{
                index++
                this.wxpopTip.c = c.slice(0, index)
                if(index==8){
                  clearInterval(time)
                }
              },100)
            }
            return sleep(900)
          }).then(()=>{
            let index = 0
            let time = null
            if(time==null){
              time = setInterval(()=>{
                index++
                this.wxpopTip.b = b.slice(0, index)
                if(index==10){
                  clearInterval(time)
                }
              },100)
            }
          })
        }
      }).catch(err=>{
        console.log(err)
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if(vm.$store.state.username || localStorage.getItem('userToken')){
        /*判断当前用户是否登录 已登录就返回首页*/
        // vm.$toast.fail("请先退出登录");
        /*if (from.path !== "/register" &&  from.path!== "/login") {
          alert(from.path)
          vm.$router.go(-1)
        }*/
        vm.$router.replace("/")
      }
      vm.beforfrom = from.path
    })
  },
}
</script>

<style scoped>
.wxlogin{
  display: flex;
  justify-content: center;
  align-items: center;
  white-space: nowrap;
  flex-direction: column;
  clear: both;
  margin-top: 70px;
}
.wxlogin .icon{
  width: 50px;
  height: 50px;
  background: url('../../assets/wxlogin.png') 0 0/100% 100% no-repeat;
  border-radius: 50%;
}
.wxlogin .tip{
  margin: 5px 0 0;
  font-size: 12px;
}
.wxpop{
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.25);
}
.wxpop_main{
  width: 50%;
  min-width: 300px;
  height: 60vh;
  background: #ffffff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border-radius: 10px;
  box-shadow: 6px 4px 10px rgba(0, 0, 0, 0.4);
}
.wxpop_close{
  width: 30px;
  height: 30px;
  background: url("../../assets/wxclose.png") center center/contain no-repeat;
  position: absolute;
  right: -12px;
  top: -12px;
  transform: rotate(0deg);
  transform-origin: center center;
}
.an_wxpop_close{
  animation: close 1s infinite linear ;
}
.wxpop_title{
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  height: 49px;
  padding-top: 20px;
}
.wxpop_wxqr{
  width: 100%;
  height: calc(60vh - 230px);
  margin: 20px auto 0;
  text-align: center;
  /*background: url("../../assets/wxqr.jpg") center center/contain no-repeat;*/
}
.wxpop_wxqr img{
  margin: 0 auto;
}

.popshow-leave-active{
  animation: wxpop .5s reverse linear;
}
.popshow-enter-active{
  animation: wxpop .5s linear;
}
@keyframes wxpop {
  0%{
    opacity: 0;
  }
  100%{
    opacity: 1;
  }
}
@keyframes close {
  0%{
    transform: rotate(0deg);
  }
  100%{
    transform: rotate(360deg);
  }
}
</style>
